package com.xuebusi.orm.mybatis.session;

import com.xuebusi.orm.mybatis.binding.MappedProxy;
import com.xuebusi.orm.mybatis.config.Configuration;
import com.xuebusi.orm.mybatis.config.MappedStatement;
import com.xuebusi.orm.mybatis.excutor.DefaultExecutor;
import com.xuebusi.orm.mybatis.excutor.Executor;

import java.lang.reflect.Proxy;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration conf;

    private Executor executor;

    DefaultSqlSession(Configuration conf) {
        super();
        this.conf = conf;
        executor = new DefaultExecutor(conf);
    }

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        List<T> ret = this.selectList(statement, parameter);
        if (ret == null || ret.size() == 0) {
            return null;
        }
        if (ret.size() > 1) {
            throw new RuntimeException("too many results!!!!");
        }
        return ret.get(0);
    }

    @Override
    public <E> List<E> selectList(String statement, Object parameter) {
        MappedStatement ms = conf.getMappedStatements().get(statement);
        return executor.query(ms, parameter);
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        MappedProxy mp = new MappedProxy(this);
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, mp);
    }
}
